package com.mfks.web;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.mfks.model.MemberPhoto;
import com.mfks.model.TMember;
import com.mfks.model.TMemberPhoto;
import com.mfks.model.TMemberTest;
import com.mfks.service.MemberPhotoService;
import com.mfks.service.MemberService;
import com.mfks.service.MemberTestService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import top.ibase4j.core.base.AppBaseController;
import top.ibase4j.core.support.Assert;
import top.ibase4j.core.util.CacheUtil;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.DateUtil;
import top.ibase4j.core.util.InstanceUtil;
import top.ibase4j.core.util.UploadUtil;
import top.ibase4j.core.util.WebUtil;
import top.ibase4j.model.Login;

/**
 * <p>
 * 会员 前端控制器
 * </p>
 *
 * @author ShenHuaJie
 * @since 2017-03-19
 */
@RestController
@RequestMapping("/app/member/")
@Api(value = "会员管理接口", description = "APP-个人中心-个人信息管理接口")
public class MemberController extends AppBaseController<TMember, MemberService> {
    private MemberPhotoService memberPhotoService;
    private MemberTestService memberTestService;

    @ApiOperation(value = "查询会员数", produces = MediaType.APPLICATION_JSON_VALUE, response = Integer.class)
    @RequestMapping(value = "count", method = {RequestMethod.GET, RequestMethod.POST})
    public Object queryCount(HttpServletRequest request) {
        Map<String, Object> param = WebUtil.getParameter(request);
        String minAge = (String)param.get("minAge");
        String maxAge = (String)param.get("maxAge");
        if (DataUtil.isNotEmpty(minAge)) {
            param.put("startDate", DateUtil.addDate(new Date(), Calendar.YEAR, -Integer.parseInt(minAge)));
        }
        if (DataUtil.isNotEmpty(maxAge)) {
            param.put("endDate", DateUtil.addDate(new Date(), Calendar.YEAR, -Integer.parseInt(maxAge)));
        }
        Integer result = service.count(param);
        return setSuccessModelMap(result);
    }

    @ApiOperation(value = "查询会员", produces = MediaType.APPLICATION_JSON_VALUE, response = TMember.class)
    @RequestMapping(value = "query", method = {RequestMethod.GET, RequestMethod.POST})
    public Object queryBaseInfo(HttpServletRequest request) {
        Map<String, Object> param = WebUtil.getParameter(request);
        TMember member = service.getInfo(getCurrUser(request));
        if (param.get("sex") == null) {
            if (member.getSex() != null) {
                param.put("sex", "1".equals(member.getSex()) ? "2"
                    : "2".equals(member.getSex()) ? "1" : "女".equals(member.getSex()) ? "男" : "女");
            }
            if (member.getMarriage() != null) {
                if (member.getMarriage().getTemper() != null && !"0".equals(member.getMarriage().getTemper())
                        && !"不限".equals(member.getMarriage().getTemper())) {
                    param.put("temper", member.getMarriage().getTemper());
                }
                if (member.getMarriage().getHeartMinds() != null && !"4".equals(member.getMarriage().getHeartMinds())
                        && !"无所谓讲情还是讲理".equals(member.getMarriage().getHeartMinds())) {
                    param.put("heartMinds", member.getMarriage().getHeartMinds());
                }
                if (member.getMarriage().getTogetherImportant() != null) {
                    param.put("togetherImportant", member.getMarriage().getHeartMinds());
                }
                if (member.getMarriage().getDefectStyle() != null) {
                    param.put("defectStyle", member.getMarriage().getDefectStyle());
                }
            }
        }
        TMemberTest entity = new TMemberTest().setMemberId(getCurrUser(request));
        List<TMemberTest> list = memberTestService.queryList(entity);
        if (!list.isEmpty()) {
            for (TMemberTest memberTest : list) {
                param.put("test" + memberTest.getTestType() + "Result", memberTest.getTestResult());
            }
        }
        Object result = service.queryBaseInfo(param);
        return setSuccessModelMap(result);
    }

    @ApiOperation(value = "获取个人信息", produces = MediaType.APPLICATION_JSON_VALUE, response = TMember.class)
    @RequestMapping(value = "getInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public Object get(HttpServletRequest request, Long id) {
        Assert.notNull(id, "ID");
        TMember result = service.getInfo(id);
        result.setPassword(null);
        return setSuccessModelMap(result);
    }

    @ApiOperation(value = "获取个人钥匙数", produces = MediaType.APPLICATION_JSON_VALUE, response = TMember.class)
    @RequestMapping(value = "getKeyNum", method = {RequestMethod.GET, RequestMethod.POST})
    public Object getKeyNum(HttpServletRequest request) {
        TMember result = service.getInfo(getCurrUser(request));
        return setSuccessModelMap(result.getKeyNum());
    }

    @Override
    @PostMapping("modifyInfo")
    @ApiOperation(value = "修改个人信息", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object update(HttpServletRequest request, TMember member) {
        Long id = getCurrUser(request);
        member.setId(id);
        Assert.notNull(member.getId(), "ID");
        TMember user = service.queryById(member.getId());
        Assert.notNull(user, "MEMBER", member.getId());
        service.updateAll(member);
        return super.setSuccessModelMap();
    }

    @PostMapping("uploadAvatar")
    @ApiOperation(value = "修改个人头像", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object uploadAvatar(HttpServletRequest request, MemberPhoto param) {
        Long id = getCurrUser(request);
        if (DataUtil.isNotEmpty(id)) {
            param.setMemberId(id);
        }
        Assert.notNull(param.getMemberId(), "ID");
        List<String> avatars = UploadUtil.uploadImage(request, false);
        org.springframework.util.Assert.notEmpty(avatars, "头像数据dataFile不能为空");
        TMember member = new TMember();
        member.setId(param.getMemberId());
        TMember user = service.queryById(member.getId());
        Assert.notNull(user, "MEMBER", member.getId());
        String filePath = UploadUtil.getUploadDir(request) + avatars.get(0);
        String avatar = UploadUtil.remove2FDFS(filePath).getRemotePath();
        member.setAvatar(avatar);
        Long userId = getCurrUser(request);
        member.setUpdateBy(userId);
        member.setUpdateTime(new Date());
        service.update(member);
        Map<String, Object> result = InstanceUtil.newHashMap("bizeCode", 1);
        result.put("avatar", avatar);
        return setSuccessModelMap(result);
    }

    @PostMapping("uploadPhoto")
    @ApiOperation(value = "上传图片", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object uploadPhoto(HttpServletRequest request, MemberPhoto param) {
        Long id = getCurrUser(request);
        if (DataUtil.isNotEmpty(id)) {
            param.setMemberId(id);
        }
        Assert.notNull(param.getMemberId(), "ID");
        List<String> avatars = UploadUtil.uploadImage(request, false);
        org.springframework.util.Assert.notEmpty(avatars, "头像数据dataFile不能为空");
        TMember member = new TMember();
        member.setId(param.getMemberId());
        TMember user = service.queryById(member.getId());
        Assert.notNull(user, "MEMBER", member.getId());
        String filePath = UploadUtil.getUploadDir(request) + avatars.get(0);
        String avatar = UploadUtil.remove2FDFS(filePath).getRemotePath();
        TMemberPhoto memberPhoto = new TMemberPhoto().setMemberId(id).setPhoto(avatar);
        memberPhoto.setCreateBy(id);
        memberPhoto.setUpdateBy(id);
        memberPhoto.setCreateTime(new Date());
        memberPhoto.setUpdateTime(new Date());
        memberPhotoService.update(memberPhoto);
        Map<String, Object> result = InstanceUtil.newHashMap("bizeCode", 1);
        result.put("url", avatar);
        return setSuccessModelMap(result);
    }

    @PostMapping("updatePhoneByIdCard")
    @ApiOperation(value = "修改个人手机号", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object updatePhone(HttpServletRequest request, String newPhone, String orderPhone, String idCard,
        String realname) {
        Map<String, Object> parame = WebUtil.getParameter(request);
        Object result = service.updataphone(parame);
        return setSuccessModelMap(result);
    }

    @PostMapping("updatePhoneByPhone")
    @ApiOperation(value = "修改个人手机号", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object updatePhone(HttpServletRequest request, Login user, String memberId) {
        Assert.notNull(user.getAccount(), "ACCOUNT");
        Assert.notNull(user.getPassword(), "PASSWORD");
        String password = (String)CacheUtil.getCache().get("CHGINFO_" + user.getAccount());
        if (user.getPassword().equals(password)) {
            TMember tMember = new TMember();
            tMember.setPhone(user.getAccount());
            tMember.setId(Long.parseLong(memberId));
            return super.update(request, new ModelMap(), tMember);
        }
        return setSuccessModelMap("验证码错误");
    }

    @ApiOperation("实名认证")
    @PostMapping("/authentication")
    public Object authentication(HttpServletRequest request, String memberId, String realName, String idCard) {
        Map<String, Object> param = WebUtil.getParameter(request);
        Object result = service.authentication(param);
        return setSuccessModelMap(result);
    }

    @PostMapping("badReview")
    @ApiOperation(value = "差评", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object badReview(HttpServletRequest request, Long memberId) {
        TMember record = service.queryById(memberId);
        record.setBadReviewNum(DataUtil.ifNull(record.getBadReviewNum(), 0) + 1);
        service.update(record);
        return setSuccessModelMap();
    }
}
